package com.replication.jdbc;

import com.replication.log.Logger;

import java.util.ArrayList;
import java.util.List;

public class URLParser {
    private static Logger logger = Logger.getLogger(URLParser.class);
    private String replicationUrl;
    private String masterUrl;
    private final List<String> slaverUrlList = new ArrayList();

    public URLParser(String replicationUrl) {
        this.replicationUrl = replicationUrl;
        this.parser();
    }

    private void parser() {
        logger.debug("{Parser URL} " + this.replicationUrl);
        String driverPrefix = this.replicationUrl.substring(URLPrefix.URL_PREFIX.length(), this.replicationUrl.indexOf("//"));
        String dbserverHostsStr = this.replicationUrl.substring(this.replicationUrl.indexOf("//") + 2, this.replicationUrl.lastIndexOf(47));
        String databaseOpts = this.replicationUrl.substring(this.replicationUrl.lastIndexOf(47) + 1);
        String[] dbserverHosts = dbserverHostsStr.split(",");
        this.masterUrl = driverPrefix + "//" + dbserverHosts[0] + "/" + databaseOpts;
        logger.debug("{master url} " + this.masterUrl);

        for(int i = 1; i < dbserverHosts.length; ++i) {
            String slaverUrl = driverPrefix + "//" + dbserverHosts[i] + "/" + databaseOpts;
            this.slaverUrlList.add(slaverUrl);
            logger.debug("{slaver url} " + slaverUrl);
        }

    }

    public String getMasterUrl() {
        return this.masterUrl;
    }

    public String getSlaverUrl(int index) {
        return (String)this.slaverUrlList.get(index);
    }

    public int getSlaverCount() {
        return this.slaverUrlList.size();
    }

    public String[] getSlaverUrlAsArray() {
        int count = this.getSlaverCount();
        if(count == 0) {
            return null;
        } else {
            String[] result = new String[count];

            for(int i = 1; i < count; ++i) {
                result[i] = (String)this.slaverUrlList.get(i);
            }

            return result;
        }
    }

    public List<String> getSlaverUrl() {
        return this.slaverUrlList;
    }
}
